<?php

declare(strict_types=1);

namespace App\Controller\Admin;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Model\AdminUser;
use App\Utils\UserUtils;
use App\Utils\JwtToken;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\AdminMiddleware;

/**
 * @AutoController(prefix="/admin/user")
 */
class User extends AbstractController
{
    public function login() {
        $this->validate([
            'username' => 'required',
            'password' => 'required'
        ]);
        
        $user = AdminUser::query()
            ->where('username', $this->request->input('username'))
            ->first();
        
        if ($user == null) {
            return $this->error('账号不存在');
        }
        if ($user->password != UserUtils::password($this->request->input('password'))) {
            return $this->error('账号或密码错误');
        }
        if ($user->status == 0) {
            return $this->error('账号被禁止登陆');
        }

        $token = JwtToken::encode([
            'id' => $user->id
        ], 'admin-key');
        $user->token = $token;
        $user->save();

        // unset($user->password);
        return $this->success($token);
    }

    /**
     * @Middlewares({
     *     @Middleware(AdminMiddleware::class)
     * })
     */
    public function profile() {
        $user = AdminUser::find($this->request->getHeader('admin_user_id')[0]);
        $role = $user->role;
        $role->menus = $role->menus()->orderBy('sorting', 'desc')->get();

        unset($user->password);
        return $this->success($user);
    }

    /**
     * @Middlewares({
     *     @Middleware(AdminMiddleware::class)
     * })
     */
    public function info() {
        $this->validate([
            'id' => 'required'
        ]);
        $user = AdminUser::find($this->request->input('id'));
        return $this->success($user);
    }

    /**
     * @Middlewares({
     *     @Middleware(AdminMiddleware::class)
     * })
     */
    public function list() {
        $data = $this->request->all();
        $query = AdminUser::query();

        if (!empty($data['nickname'])) {
            $query = $query->where('nickname', 'like', '%'.$data['nickname'].'%');
        }
        if (!empty($data['role_id'])) {
            $query = $query->where('role_id', $data['role_id']);
        }

        if (!empty($data['status'])) {
            $query = $query->where('status', $data['status']);
        }

        $query = $query->with('role')
            ->orderBy('id', 'desc');
        if (isset($data['page_size']) && $data['page_size'] <= 0) {
            $list = $query->get();
        }else{
            $list = $query->paginate($data['page_size'] ?? 20);
        }
        foreach ($list as &$item) {
            unset($item->password);
            unset($item->token);
        }
        return $this->success($list);
    }

    /**
     * @Middlewares({
     *     @Middleware(AdminMiddleware::class)
     * })
     */
    public function save() {
        $this->validate([
            'username' => 'required|alpha_dash|between:1,20',
            'password' => 'filled|alpha_dash|between:1,20',
            'role_id' => 'required|integer',
            'status' => 'boolean'
        ]);

        $data = $this->request->all();

        $query = AdminUser::query()
            ->where('username', $data['username']);
        if (!empty($data['id'])) {
            $query = $query->where('id', '<>', $data['id']);
        }
        if ($query->count() > 0) {
            return $this->error('用户名已存在');
        }

        if (!empty($data['password'])) {
            $data['password'] = UserUtils::password($data['password']);
        }

        $model = AdminUser::upsert($data);
        if (empty($model->password)) {
            $model->password = UserUtils::password('123456');
            $model->save();
        }

        return $this->success($model);
    }

    /**
     * @Middlewares({
     *     @Middleware(AdminMiddleware::class)
     * })
     */
    public function delete() {
        // $id = $this->request->input('id');
        // if (empty($id)) return $this->error('id不能为空');
        $this->validate([
            'id' => 'required'
        ]);
        $id = $this->request->input('id');
        $myid = $this->request->getHeader('admin_user_id')[0];
        if ($myid == $id) {
            return $this->error('不能删除自己');
        }

        $user = AdminUser::find($id);
        if ($user->role_id == 1) {
            $adminCount = AdminUser::query()->where('role_id', 1)->count();
            if ($adminCount <= 1) {
                return $this->error('不能删除唯一的超级管理员');
            }
        }

        $res = $user->delete();
        return $this->success($res);
    }
}
